/**
 * Copyright (c) 2020 铭软科技(mingsoft.net)
 * 本软件及相关文档文件（以下简称“软件”）的版权归 铭软科技 所有
 * 遵循铭软科技《保密协议》
 */


package net.mingsoft.basic.action.web;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.constant.Const;
import net.mingsoft.basic.biz.IAppBiz;
import net.mingsoft.basic.entity.AppEntity;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.SpringUtil;
import net.mingsoft.mwebsite.biz.IWebsiteBiz;
import net.mingsoft.mwebsite.entity.WebsiteEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author by 铭飞开源团队
 * @Description TODO
 * @date 2020/1/10 8:39
 */
@Controller("indexAction")
@RequestMapping("index")
public class IndexAction {

    private static String  INDEX = "index.html", DEFAULT = "default.html";
    /**
     * 注入站点业务层
     */
    private IAppBiz appBiz;
    /**
     * appBiz业务层的注入
     */
    @Autowired
    private IWebsiteBiz websiteBiz;

    /**
     * 访问站点主页
     *
     * @param req
     *            HttpServletRequest对象
     * @param res
     *            HttpServletResponse 对象
     * @throws ServletException
     *             异常处理
     * @throws IOException
     *             异常处理
     */
    @ApiOperation(value = "访问站点主页")
    @RequestMapping
    public String index( HttpServletRequest req, HttpServletResponse res, ModelMap mode) throws IOException {
// 获取用户所请求的域名地址
        WebsiteEntity _website = websiteBiz.getByUrl(BasicUtil.getDomain());
        if(_website.getWebsiteState()==1){
            mode.addAttribute("err", "站点已停止服务");
            return "/errors/stop";
        }
        appBiz = SpringUtil.getBean(IAppBiz.class);
        AppEntity website = appBiz.getOne(Wrappers.<AppEntity>lambdaQuery().like(AppEntity::getAppUrl, BasicUtil.getDomain()),false);
        String dir = "";
        if (website != null) {
            dir = website.getAppDir();
        } else {
            return "";
        }

        String defaultHtmlPath = BasicUtil.getRealPath("html" + File.separator + dir + File.separator + "default.html");
        File file = new File(defaultHtmlPath);
        String url = "html" + Const.SEPARATOR + dir ;
        String indexPosition = url + Const.SEPARATOR + INDEX;
        if (file.exists()) {
            indexPosition = url + Const.SEPARATOR + DEFAULT;
        }
        return "forward:"+indexPosition;
    }
}
